package com.hospital.ecard.xmlutils;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * @author lvyao
 * @description xml整合
 * @date 2020/7/1
 */
public class XmlUtils {
    public static String convertToXml(Object object) {
        StringWriter sw = new StringWriter();
        try {
            JAXBContext context = JAXBContext.newInstance(object.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
            marshaller.marshal(object, sw);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return sw.toString();
    }

    public static <T> T xmlToBean(String xml, String elementName, Class<T> cls) {
        T object = null;
//        Map<String, String> map = new HashMap<String, String>();
        try {
            Document document = DocumentHelper.parseText(xml);
            String beanXml = document.getRootElement().element("Body").element(elementName).element("return").asXML();
            JAXBContext context = JAXBContext.newInstance(cls);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            StringReader sr = new StringReader(beanXml);
            object = (T) unmarshaller.unmarshal(sr);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return object;
    }
}
